﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Apex.Common.Models;

namespace Apex.Common.MVVM
{
    public class CollectionViewModel<T, K, Z> : ViewModel<T>
        where T : ICollectionContainer<Z>
        where K : IViewModel
    {
        protected ObservableCollection<K> _items;

        public ObservableCollection<K> Items
        {
            get { return _items; }
            set
            {
                _items = value;
                _items.CollectionChanged += _items_CollectionChanged;
                OnPropertyChanged("Items");
            }
        }

        protected void _items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
            {
                foreach (var x in e.NewItems)
                {
                    ((T)Model).Items.Add((Z)((K)x).GetType().GetProperty("Model").GetValue(x));
                }
            }

            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                foreach (var x in e.OldItems)
                {
                    ((T)Model).Items.Remove((Z)((K)x).GetType().GetProperty("Model").GetValue(x));
                }
            }

            OnPropertyChanged("Items");
        }


        public CollectionViewModel()
            : base()
        {
            _items = new ObservableCollection<K>();
            _items.CollectionChanged += _items_CollectionChanged;
        }

        public CollectionViewModel(T model)
            : base(model)
        {
            _items = new ObservableCollection<K>();
            _items.CollectionChanged += _items_CollectionChanged;
        }
    }
}
